<?php

namespace Users\Recover;

use Pinenut\Action;
use Pinenut\Form;
use Pinenut\User\Auth\EmailPassword;
use Users\Recover\CheckCodeFormConfig as FormConfig;

class CheckCodeAction extends Action
{
	protected static $layout = "#layouts.column1Narrow";

	public function run()
	{
		$formConfig = FormConfig::get();
		$form = new Form($this->request->getSessionId(), 'checkCode', $formConfig);
		
		if ($this->request->isPost() && $this->request->isAjax()) {
			$form->process($this->request->params(), true);
			$this->response->content = $form->render();
			$this->response->noRender(true);
			return;
		} else if ($this->request->isPost() && !$this->request->onlyRender) {
			if (!$form->process($this->request->params())) {
				$this->response->form = $form;
				return;
			}
			$values = $form->getValues();
			$auth = EmailPassword::setRecoveryPassword($values['email'], 
					$values['recoveryCode'], $values['newPassword']);
			
			if ($auth) {
				$ref = $auth->profile->get ();
				if ($ref) {
					$profile = $ref->getEntity ();
				}
				if (! $profile) {
					throw new \Exception ( 'Profile not found' );
				}
				// аутентифицируем
				\Application::auth ()->login ( ( string ) $profile );
				$form->flush();
				$this->redirect($this->url(''));
			} 
		}
		
		$this->response->form = $form;
	}
}